package com.fishleap.handler;

import com.fishleap.dto.RpcRequest;
import com.fishleap.service.UserServiceImpl;
import com.fishleap.util.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author zlg
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {


    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        // 1.判断当前请求是否是RpcRequest对象
        if (msg instanceof RpcRequest) {
            // 2.获取请求中的相关信息
            String interfaceName = ((RpcRequest) msg).getInterfaceName();
            String methodName = ((RpcRequest) msg).getMethodName();
            Class<?>[] paramTypes = ((RpcRequest) msg).getParamTypes();
            Object[] parameters = ((RpcRequest) msg).getParameters();
            // 3.使用反射生成字节码对象并调用相关方法,从spring容器中获取对象
            Class<?> aClass = Class.forName(interfaceName);
            Object result = aClass.getDeclaredMethod(methodName, paramTypes)
                                  .invoke(SpringUtil.getBean(aClass), parameters);
            //4.把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(result);
        }

    }



    //当客户端读取数据时,该方法会被调用
    public void channelReadString(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
        //1.判断当前的请求是否符合规则
        if (msg.toString().startsWith("UserService")) {
            //2.如果符合规则,调用实现类得到一个result
            UserServiceImpl userService = new UserServiceImpl();
            String result = userService.sayHelloString(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            //3.把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(result);
        }

    }
}
